//
//  RetweetPictureView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/22.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

//配图的大小
let margin: CGFloat = 4
//如果不是单图,每张图片显示的是正方形
// 每一个条目的宽高 (collectionView item 的宽高，尽量设置成整数),不然图片显示会有问题
let itemWHInt = Int((SCREENW - 2 * StatusCellMargin - 2 * margin) / 3)
let itemWH = CGFloat(itemWHInt)

class RetweetPictureView: UICollectionView {
    
    let RetweetPicCellID = "RetweetPicCellID"
    
    //元组
    var dataInfo:(pic_urls:[PictureModel],size:CGSize)?{
        
        didSet{
            
            if dataInfo?.pic_urls.count == 1{
                
                let retweetPic = self.collectionViewLayout as! UICollectionViewFlowLayout
                retweetPic.itemSize = dataInfo?.size ?? CGSizeZero
            }else{
                let retweetPic = self.collectionViewLayout as! UICollectionViewFlowLayout
                retweetPic.itemSize = CGSizeMake(itemWH, itemWH)
            }
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.size.equalTo(dataInfo?.size ?? CGSizeZero)
            }
            
            reloadData()
//            self.pictures = pictures
            
//            if pictures.count == 1{
//                
//                let retweetPic = retweetPicView.collectionViewLayout as! UICollectionViewFlowLayout
//                retweetPic.itemSize = statusViewModel!.retweetPicViewSize
//            }else{
//                
//                let retweetPic = retweetPicView.collectionViewLayout as! UICollectionViewFlowLayout
//                retweetPic.itemSize = CGSizeMake(itemWH, itemWH)
//            }
//            
//            retweetPicView.snp_updateConstraints(closure: { (make) -> Void in
//                
//                make.size.equalTo(statusViewModel!.retweetPicViewSize)
//            })
//            
//            //设置数据 (根据数据计算出配图视图的大小并设置上去)
//            retweetPicView.pictures = pictures
        }
    }
    
//    var pictures: [PictureModel]?{
//        
//        didSet{
//            
//            countLabel.text = "\(pictures?.count ?? 0)"
//            
//            //----- ******** 刷新
//            reloadData()
//        }
//    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.lightGrayColor()
        
        //注册cell
        registerClass(RetweetPicViewCell.self, forCellWithReuseIdentifier: RetweetPicCellID)
        
        //拿到 布局对象
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置item大小
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        //设置最小间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        // 在这种情况下，因为当前控件是一个collectionView，而当前控件持有数据，所以就可以将数据源设置成自己
        self.dataSource = self
        self.delegate = self
        
        //添加控件
        addSubview(countLabel)
        
        //添加约束
        countLabel.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self)
        }
    }
    
    //懒加载
    private lazy var countLabel: UILabel = UILabel(textFont: 30, textColor: UIColor.purpleColor())
    
}

// MARK: - collectionView 数据源 ~ 代理
extension RetweetPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //        print(pictures?.count)
//        return pictures?.count
        return dataInfo?.pic_urls.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RetweetPicCellID, forIndexPath: indexPath) as! RetweetPicViewCell
        
        //        cell.backgroundColor = RandomColor
        
//        cell.photoInfo = pictures![indexPath.item]
        cell.photoInfo = dataInfo?.pic_urls[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        //        photoBrowser.delegate = self;
        //        photoBrowser.currentImageIndex = indexPath.item;
        //        photoBrowser.imageCount = self.modelsArray.count;
        //        photoBrowser.sourceImagesContainerView = self.collectionView;
        //
        //        [photoBrowser show];
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = dataInfo!.pic_urls.count
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
        
    }
    
}

extension RetweetPictureView:SDPhotoBrowserDelegate{
    
    //缩略图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! RetweetPicViewCell
        return cell.pictureView.image
    }
    
    //高清图
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let url = (dataInfo!.pic_urls[index].thumbnail_pic! as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: url)
    }
}

//创建一个cell类
class RetweetPicViewCell: UICollectionViewCell{
    
    var photoInfo: PictureModel?{
        
        didSet{
            
            pictureView.sd_setImageWithURL(NSURL(string:photoInfo?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            
            //判断是否为gif动图(是否以.gif结尾)
//            gif.hidden = (photoInfo?.thumbnail_pic ?? "").hasSuffix(".gif") ? false : true
            gif.hidden = !(photoInfo?.thumbnail_pic ?? "").hasSuffix(".gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = RandomColor
        
        //        添加控件
        contentView.addSubview(pictureView)
        contentView.addSubview(gif)
        
        //        添加约束
        pictureView.snp_makeConstraints { (make) -> Void in
            
            //以下2中方式设置约束效果一样
            make.edges.equalTo(contentView)
            //            make.leading.top.bottom.trailing.equalTo(contentView)
        }
        
        gif.snp_makeConstraints { (make) -> Void in
            
            make.trailing.bottom.equalTo(pictureView)
        }
    }
    
    //    懒加载图片
    private lazy var pictureView: UIImageView = {
        
        let imgView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        
        //图片的填充模式
        imgView.contentMode = .ScaleAspectFill
        
        //超出图片框的部分进行切割
        imgView.clipsToBounds = true
        
        return imgView
    }()
    
    //    懒加载gif
    private lazy var gif: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}


